package controller

import (
	"gddgame.cc/galaxy/common"
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/models"

	"gddgame.cc/galaxy/utils/def"
)

// app服务端访问平台及外部服务的签名
func ValidSign(context def.Context, appKey string, noise string, sign string) (*models.App, error) {
	var app models.App
	var err error
	var ok bool
	err = wrap.Cache("app/key/"+appKey, &app, func() error {
		if ok, err = models.AppModel.Query().Where("=", "app_key", appKey).One(&app); ok {
			return EmptyExceptionDetail("app不存在", err)
		}
		return nil
	})
	content := map[string]interface{}{
		"secret":  app.AppSecret,
		"noise":   noise,
		"app_key": appKey,
	}
	signReal := common.SignSha1(content)
	if sign != signReal {
		return nil, ValidException("签名错误")
	}
	return &app, nil
}

// app服务器接受客户端的请求链接验证
func ValidToken(context def.Context, appId string, appToken string) (*models.App, error) {
	var app models.App
	var err error
	var ok bool
	err = wrap.Cache("app/id/"+appId, &app, func() error {
		if ok, err = models.AppModel.Query().Where("=", "app_id", appId).One(&app); !ok {
			return EmptyExceptionDetail("app不存在", err)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	if app.AppToken != appToken {
		return nil, ValidException("token错误")
	}
	return &app, nil
}
